package com.mybatis.boost.id;

import javax.annotation.Nullable;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author jearton
 * @since 2017/2/7
 */
public class IdHelper {

    private static final String TIME_TOKEN_FORMAT = "yyMMddHHmmssSSS";

    private static IdGenerator idGenerator = new IdGenerator();

    /**
     * 全局分布式唯一ID
     */
    public static long getId() {
        return idGenerator.nextId();
    }

    /**
     * 生成唯一键中的时间戳，默认格式：yyMMddHHmmssSSS
     */
    public static String getTimeToken() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(TIME_TOKEN_FORMAT);
        ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
        return formatter.format(now);
    }

    /**
     * 32位UUID
     */
    public static String get32UUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 在启动期间尝试重设nodeId，如果有外部配置的话
     */
    static void reload(@Nullable Long nodeId) {
        if (nodeId != null && nodeId > 0) {
            idGenerator = new IdGenerator(nodeId);
        }
    }
}
